package org.gruposp2p.openid

import org.gruposp2p.openid.provider.UserDNI;
//import org.springframework.security.providers.UsernamePasswordAuthenticationToken as AuthToken
//import org.springframework.security.context.SecurityContextHolder as SCH
import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH

/**
 * Registration controller.
 */
class RegisterController {

	def springSecurityService
	def messageSource
	def emailerService

	static Map allowedMethods = [save: 'POST', update: 'POST']

	/**
	 * User Registration Top page.
	 */
	def index = {
		if (springSecurityService.isLoggedIn()) {
			redirect action: show
			return
		}
		if (session.id) {
			def user = new UserDNI()
			user.properties = params
			return [user: user]
		}

		redirect uri: '/'
	}

	/**
	 * User Information page for current user.
	 */
	def show = {
		def principal = springSecurityService.principal
		def user = UserDNI.get(principal.id)
		if (user) {
			render view: 'show', model: [user: user]
		}
		else {
			redirect action: index
		}
	}

	/**
	 * Edit page for current user.
	 */
	def edit = {
		def user
		def principal = springSecurityService.principal
		if (principal) {
			user = UserDNI.get(principal.id)
		}
		if (!user) {
			//def msg = messageSource.resolveCode("message.code.to.translate", new java.util.Locale("EN")).format(testArgs)
			flash.message = messageSource.resolveCode("register.userNotFound", request.locale).format(params.id)
			//flash.message = "[Illegal Access] User not found with id ${params.id}"
			redirect action: index
			return
		}

		[user: user]
	}

	/**
	 * update action for current user's edit page
	 */
	def update = {
		def user
		def principal = springSecurityService.principal
		if (principal) {
			user = UserDNI.get(principal.id)
		}
		else {
			redirect action: index
			return
		}

		if (!user) {
			flash.message = messageSource.resolveCode("register.userNotFound", request.locale).format(params.id)
			redirect action: index, id: params.id
			return
		}

		// if user want to change password. leave passwd field blank, passwd will not change.
		if (params.passwd && params.passwd.length() > 0
				&& params.repasswd && params.repasswd.length() > 0) {
			if (params.passwd == params.repasswd) {
				user.password = springSecurityService.encodePassword(params.passwd)
			} else {
				user.password = ''
				flash.message = messageSource.resolveCode("register.passwordNotMatch", request.locale)
				render view: 'edit', model: [user: user]
				return
			}
		}
		user.username = params.userRealName
		person.email = params.email

		if (person.save()) {
			redirect action: show, id: person.id
		}
		else {
			render view: 'edit', model: [user: user]
		}
	 }

	/**
	 * User save action.
	 */
	def save = {
		if (springSecurityService.isLoggedIn()) {
			redirect action: show
			return
		}

		def user = new UserDNI()
		user.properties = params

		def defaultRole = CH.config.security.defaultRole

		def role = RoleDNI.findByAuthority(defaultRole)
		if (!role) {
			user.password = ''
			flash.message = messageSource.resolveCode("register.DefaultRoleNotFound", request.locale)
			render view: 'index', model: [user: user]
			return
		}

		if (params.captcha.toUpperCase() != session.captcha) {
			user.passwd = ''
			flash.message = messageSource.resolveCode("register.AccessCodeError", request.locale)
			render view: 'index', model: [user: user]
			return
		}

		if (params.passwd != params.repasswd) {
			user.password = ''
			flash.message = messageSource.resolveCode("register.passwordNotMatch", request.locale)
			render view: 'index', model: [person: person]
			return
		}

		user.password = springSecurityService.encodePassword(params.passwd)
		user.enabled = true
		user.accountNonExpired = true
		user.accountNonLocked = true
		user.credentialsNonExpired = true	
		if (user.save()) {
			UserDNIRoleDNI.create user, role, true
			if (CH.config.security.useMail) {
				String emailContent = """You have signed up for an account at:

 ${request.scheme}://${request.serverName}:${request.serverPort}${request.contextPath}

 Here are the details of your account:
 -------------------------------------
 OpenID identifier: ${user.userOpenID}
 User name: ${user.username}
 NIF: ${user.nif}
 Email: ${user.email}					
"""

				def email = [
					to: [user.email], // 'to' expects a List, NOT a single email address
					subject: "[${user.userOpenID}] Account Signed Up",
					text: emailContent // 'text' is the email body
				]
				emailerService.sendEmails([email])
			}

			user.save(flush: true)
			springSecurityService.reauthenticate user.username
			//def auth = new AuthToken(person.username, params.passwd)
			//def authtoken = daoAuthenticationProvider.authenticate(auth)
			//SCH.context.authentication = authtoken
			redirect uri: '/'
		}
		else {
			person.passwd = ''
			render view: 'index', model: [person: person]
		}
	}
	
}
